<template>
  <div class="auth-container">
    <div class="auth-card">
      <h2>{{ isLogin ? '登录' : '注册' }}</h2>
      <form @submit.prevent="handleSubmit">
        <div class="form-group">
          <label for="teiphon">手机号</label>
          <input
              type="tel"
              id="teiphon"
              v-model="teiphon"
              required
              placeholder="请输入手机号"
          >
        </div>

        <div class="form-group" v-if="!isLogin">
          <label for="otpCode">验证码</label>
          <div class="otp-group">
            <input
                type="text"
                id="otpCode"
                v-model="otpCode"
                required
                placeholder="请输入验证码"
            >
            <button
                type="button"
                class="get-otp-btn"
                @click="getOtp"
                :disabled="isSendingOtp"
            >
              {{ isSendingOtp ? '发送中...' : '获取验证码' }}
            </button>
          </div>
        </div>

        <div class="form-group">
          <label for="password">密码</label>
          <input
              type="password"
              id="password"
              v-model="password"
              required
              placeholder="请输入密码"
          >
        </div>

        <div class="form-group" v-if="!isLogin">
          <label for="name">姓名</label>
          <input
              type="text"
              id="name"
              v-model="name"
              required
              placeholder="请输入姓名"
          >
        </div>

        <div class="form-group" v-if="!isLogin">
          <label for="age">年龄</label>
          <input
              type="number"
              id="age"
              v-model="age"
              required
              placeholder="请输入年龄"
          >
        </div>

        <div class="form-group" v-if="!isLogin">
          <label>性别</label>
          <div class="gender-group">
            <label>
              <input type="radio" v-model="gender" value="1" checked> 男
            </label>
            <label>
              <input type="radio" v-model="gender" value="0"> 女
            </label>
          </div>
        </div>

        <button type="submit" class="submit-btn">{{ isLogin ? '登录' : '注册' }}</button>
      </form>

      <p class="toggle-text">
        {{ isLogin ? '还没有账号？' : '已有账号？' }}
        <button type="button" class="toggle-btn" @click="toggleMode">
          {{ isLogin ? '立即注册' : '立即登录' }}
        </button>
      </p>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { userAPI } from '../services/api';

const router = useRouter();

// 状态变量
const isLogin = ref(true);
const teiphon = ref('');
const password = ref('');
const otpCode = ref('');
const name = ref('');
const age = ref('');
const gender = ref('1');
const isSendingOtp = ref(false);

// 切换登录/注册模式
const toggleMode = () => {
  isLogin.value = !isLogin.value;
  // 重置表单
  otpCode.value = '';
  name.value = '';
  age.value = '';
  gender.value = '1';
};

// 获取验证码
const getOtp = async () => {
  if (!teiphon.value) {
    alert('请输入手机号');
    return;
  }

  isSendingOtp.value = true;
  try {
    await userAPI.getOtp(teiphon.value);
    alert('验证码已发送，请注意查收');

    // 60秒后可重新发送
    let countdown = 60;
    const timer = setInterval(() => {
      countdown--;
      if (countdown <= 0) {
        clearInterval(timer);
        isSendingOtp.value = false;
      }
    }, 1000);
  } catch (error) {
    alert('获取验证码失败: ' + (error.message || '未知错误'));
    isSendingOtp.value = false;
  }
};

// 提交表单
const handleSubmit = async () => {
  if (isLogin.value) {
    // 登录逻辑
    try {
      console.log('发起登录请求...'); // 调试日志
      const response = await userAPI.login(teiphon.value, password.value);
      console.log('登录响应:', response); // 调试日志
      
      // 保存登录状态
      localStorage.setItem('isLogin', 'true');
      localStorage.setItem('userPhone', teiphon.value);
      
      // 保存后端返回的完整用户信息
      if (response.data) {
        const userInfo = {
          id: response.data.id,
          name: response.data.name,
          gender: response.data.gender,
          age: response.data.age,
          teiphon: response.data.teiphon
        };
        localStorage.setItem('userInfo', JSON.stringify(userInfo));
        console.log('用户信息已保存:', userInfo);
      } else {
        console.error('登录接口未返回用户信息');
        alert('登录异常，请重试');
        return;
      }
      
      alert('登录成功');
      // 触发存储事件，通知导航栏更新状态
      window.dispatchEvent(new StorageEvent('storage', {
        key: 'isLogin',
        newValue: 'true'
      }));
      router.push('/products');
    } catch (error) {
      alert('登录失败: ' + (error.message || '未知错误'));
    }
  } else {
    // 注册逻辑
    try {
      const userInfo = {
        teiphon: teiphon.value,
        otpCode: otpCode.value,
        name: name.value,
        gender: parseInt(gender.value),
        age: parseInt(age.value),
        password: password.value
      };

      await userAPI.register(userInfo);
      alert('注册成功，请登录');
      toggleMode();
    } catch (error) {
      alert('注册失败: ' + (error.message || '未知错误'));
    }
  }
};
</script>

<style scoped>
.auth-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.auth-card {
  background-color: white;
  padding: 2rem;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  width: 100%;
  max-width: 400px;
}

h2 {
  text-align: center;
  margin-bottom: 1.5rem;
  color: #333;
}

.form-group {
  margin-bottom: 1rem;
}

label {
  display: block;
  margin-bottom: 0.5rem;
  color: #666;
}

input {
  width: 100%;
  padding: 0.8rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

.otp-group {
  display: flex;
  gap: 0.5rem;
}

.otp-group input {
  flex: 1;
}

.get-otp-btn {
  padding: 0.8rem;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  white-space: nowrap;
}

.get-otp-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.gender-group {
  display: flex;
  gap: 1rem;
  padding: 0.5rem 0;
}

.submit-btn {
  width: 100%;
  padding: 0.8rem;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  cursor: pointer;
  margin-top: 1rem;
}

.submit-btn:hover {
  background-color: #45a049;
}

.toggle-text {
  text-align: center;
  margin-top: 1rem;
  color: #666;
}

.toggle-btn {
  background: none;
  border: none;
  color: #2196f3;
  cursor: pointer;
  padding: 0;
}

.toggle-btn:hover {
  text-decoration: underline;
}
</style>